export default class CodingType {

    packageName = '';
    simpleName = '';
    /**
     * 泛型类型集
     * @type {[CodingType]}
     */
    genericTypes = [];
    arrayed = false;

    constructor(packageName = '', simpleName) {
        if (simpleName === undefined) {
            let index = packageName.lastIndexOf('.');
            if (index >= 0) {
                this.packageName = packageName.substring(0, index);
            } else {
                this.packageName = '';
            }
            this.simpleName = packageName.substring(index + 1);
        } else {
            this.packageName = packageName;
            this.simpleName = simpleName;
        }
    }

    /**
     * 如果当前类型为原生类型，转换为对应的包装类型，返回新对象，不更改当前类型的内容
     * @return {CodingType} 对应的包装类型，如果当前类型不是原生类型，则返回自身
     */
    toWrapper() {
        if (!this.packageName && this.simpleName.length > 2 && this.simpleName === this.simpleName.toLowerCase()) {
            let simpleName = this.simpleName;
            if (simpleName === 'int') {
                simpleName = 'Integer';
            } else {
                simpleName = simpleName.firstToUpperCase();
            }
            return new CodingType('java.lang', simpleName);
        }
        return this;
    }

    getName() {
        let name = this.packageName;
        if (name) {
            name += '.';
        }
        return name + this.simpleName;
    }

    addGenericType(...genericTypes) {
        for (let genericType of genericTypes) {
            if (genericType) {
                if (typeof genericType === 'string') {
                    genericType = new CodingType(genericType);
                } else if (typeof genericType === 'object' && !(genericType instanceof CodingType)) {
                    genericType = new CodingType(genericType.packageName, genericType.simpleName);
                }
                if (genericType instanceof CodingType) {
                    this.genericTypes.push(genericType.toWrapper());
                }
            }
        }
    }

    toString() {
        let s = this.simpleName;
        if (this.genericTypes.length > 0) {
            s += '<';
            for (let genericType of this.genericTypes) {
                if (genericType instanceof CodingType) {
                    s += genericType + ', ';
                }
            }
            s = s.substring(0, s.length - 2);
            s += '>';
        }
        if (this.arrayed) {
            s += '[]';
        }
        return s;
    }

}
